<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 抵扣券脚本
 */
class Cron_Ticket extends CI_Controller {
	private $redis;
	private $ticketClass;
	private $logFile;
	private $db;
	public function __construct(){  
        parent::__construct();
        if(!is_cli()){
        	header("HTTP/1.0 404 Not Found");
        	show_error('Not Found',404);
        	die;
        }

        //加载操作类
		$this->load->library('TicketClass');
		$this->ticketClass = $this->ticketclass;
		$this->db	= $this->load->database('default',true);
		$this->load->config('ticket');
    }

    /**
     * 分享赠送
     * @return [type] [description]
     */
	public function share(){
		$ticketConfig = $this->config->item('ticketConfig');
		if(!$ticketConfig['active_share']){
			writeDebug('['.date("Y-m-d H:i:s").'] 分享送抵扣券活动未开启！', 'Cron_Ticket');
			die("分享送抵扣券活动未开启");
		}

		$sdate		=	date("Y-m-d 00:00:00",time()-60);
		$date		=	date("Y-m-d",strtotime($sdate));
		$edate		=	$date." 23:59:59";
			
		$ticket_arr	=	$this->ticketClass->getAllShare($sdate,$edate,1);
		$log_arr	=	$this->ticketClass->getAllShareLog(array('date'=>$date));
		$share_list	=	array();
		if(!empty($log_arr)) foreach($log_arr as $log){
			$share_list[$log['uid']]	=	$log['uid'];
		}
		$source		=	'90003';
		$datetime	=	date("Y-m-d H:i:s");
		if(!empty($ticket_arr))foreach($ticket_arr as $items){
			$uid	=	$items['uid'];	
			if(!empty($share_list[$uid])) continue;
			$tmpArr =  $this->ticketClass->checkUserTicketNum(array('uid'=>$uid));
			if($tmpArr['ticket']>0) continue;
			try {
				$this->db->trans_start();//开始事务
				
				$log_arr=	array(
					'uid'		=>	$uid,
					'date'		=>	$date,
					'create_time'=>	$datetime,
				);
				$log_table	=	"ticket_share_log";
				if (!$this->db->insert($log_table,$log_arr)) throw new Exception('L:'.__LINE__.' 添加抵扣券分享log失败!', 1);

				
				$add_arr  =  array(
					'uid'=> $uid,
					'name' => 'ACCOUNT',//帐户
					'use_value' => 1,
					'source' => $source,
					'object' => 'ticket',
					'add_time' => date("Y-m-d H:i:s"),
				);
				
				if(!$this->ticketClass->add($add_arr)){
					throw new Exception('L:'.__LINE__." 添加用户抵扣券失败！", 1);
				}
				$this->db->trans_complete();
				$this->ticketClass->flushUserCache($uid);
			} catch (Exception $e) {
				writeDebug('['.$datetime.'] uid: '.$uid.': 处理失败! Err:'.$e->getMessage(), 'Cron_Ticket');
				$this->db->trans_rollback();
			}
		}
		echo "over";
	}
}
